package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("region")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @RequestMapping("list")
    public String list(){
        return "region/list";
    }

    /**
     * 根据parentId返回Json格式字符串地区信息
     * @return
     */
    @RequestMapping("serachRegion")
    @ResponseBody
    public Object serachRegion(Long parentId){
        List<Region> list =  regionService.selectRegionByParentId(parentId);
        // treeview 格式的字符串 ---> 存放在Map集合中
        List<Map<String,Object>> mapList = new ArrayList<Map<String, Object>>();
        // 要求格式  {text: xxx,tags:xxx,nodes:xxx}
        for (Region region : list) {
            mapList.add(region.toMap());
        }
        return mapList;
    }
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region){
       JSONResult result = new JSONResult();
        try {
            if (region.getId() != null) {
                regionService.update(region);
            }else {
                regionService.save(region);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }
}
